package com.xhb.biz.job;

import cn.hutool.json.JSONUtil;
import com.xhb.biz.constant.UserConfigConstant;
import com.xhb.biz.feign.UserTokenService;
import com.xhb.biz.po.ConfigPO;
import com.xhb.biz.service.ConfigService;
import feign.Feign;
import feign.Request;
import feign.Retryer;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.schedule.annotation.Scheduled;

import java.util.Collections;
import java.util.Map;

/**
 * 验证 token 是否有效 每小时跑一次
 * @author tanyukun
 */
@Component
//@Scheduled(cron = "0/10 * * * * ? ")
@Scheduled(cron = "0 0/1 * * * ? ")
public class UserTokenCheckJob implements Runnable {

    @Inject
    ConfigService configService;
    @Inject("${manager.url}")
    String managerServerUrl;


    @Override
    public void run() {
        ConfigPO configPo = configService.selectUserConfigByKey(UserConfigConstant.USER_TOKEN_KEY);
        if (null == configPo) {
            return;
        }
        UserTokenService userTokenService = Feign.builder()
                .options(new Request.Options(1000, 3500))
                .retryer(new Retryer.Default(5000, 5000, 3))
                .target(UserTokenService.class, managerServerUrl);
        Map<String, Object> headers = Collections.singletonMap(UserConfigConstant.USER_TOKEN_KEY, configPo.getContent());

        try {
            String result = userTokenService.checkTokenStatus(headers);
            if (!JSONUtil.parseObj(result).getBool("data", false)) {
                // token 已失效
                configService.delUserConfigByKey(UserConfigConstant.USER_TOKEN_KEY);
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
        }

    }


}
